# -*- coding:utf-8 -*-

import xlwt
import datetime
from utils.views import WdCreateAPIView
from utils.response import general_json_response, ErrorCode
from rest_framework import status
from users.models import Person, CompanyInfo, AuthUser
from ElevatorAdmin.settings import MEDIA_ROOT, DOMAIN_NAME
import os
from basic.models import ElevatorInfo
from maintenance.models import Contract, Task
import json


def person_export(company_id):
    persons = Person.objects.filter_active(service_id=company_id).order_by('create_time')
    company_name = CompanyInfo.objects.filter_active(id=company_id).first().name
    wb = xlwt.Workbook(encoding='utf-8')
    ws = wb.add_sheet(u'维保人员')
    # ws.col(0).width = 25 * 256
    # ws.col(2).width = 25 * 256
    # ws.col(3).width = 25 * 256
    # ws.col(4).width = 25 * 256
    # ws.col(5).width = 25 * 256
    # ws.col(6).width = 25 * 256
    # ws.col(7).width = 25 * 256
    # ws.col(8).width = 25 * 256
    # ws.col(9).width = 25 * 256
    # ws.col(11).width = 25 * 256
    # ws.default_height = 400
    # ws.default_row = 25 * 256
    line = 1
    ws.write(0, 0, u'维保公司')
    ws.write(0, 1, u'人员状态')
    ws.write(0, 2, u'身份证号码')
    ws.write(0, 3, u'家庭住址')
    ws.write(0, 4, u'T1证号码')
    ws.write(0, 5, u'T2证号码')
    ws.write(0, 6, u'T1证有效期')
    ws.write(0, 7, u'T2证有效期')
    ws.write(0, 8, u'合同开始时间')
    ws.write(0, 9, u'合同结束时间')
    ws.write(0, 10, u'真实姓名')
    ws.write(0, 11, u'手机号码')
    ws.write(0, 12, u'账户名')
    for person in persons:
        ws.write(line, 0, company_name)
        p_s = u'在职' if person.status == 10 else u'离职'
        ws.write(line, 1, p_s)
        ws.write(line, 2, person.card_id)
        ws.write(line, 3, person.home_addr)
        ws.write(line, 4, person.t1_card_no)
        ws.write(line, 5, person.t2_card_no)
        ws.write(line, 6, person.t1_end_time)
        ws.write(line, 7, person.t2_end_time)
        ws.write(line, 8, person.contract_start_time)
        ws.write(line, 9, person.contract_end_time)
        ws.write(line, 10, person.auth_user.real_name)
        ws.write(line, 11, person.auth_user.phone)
        ws.write(line, 12, person.auth_user.username)
        line += 1
    for i in range(line):
        ws.row(i).set_style(xlwt.easyxf('font:height ' + str(600)))
    for i in range(12):
        ws.col(i).width = 256 * 25
    t = datetime.datetime.now()
    t = t.strftime('%Y-%m-%d')
    file_name = unicode(company_name) + u'维保人员' + unicode(t) + u'.xls'
    p = '%s/%s' % (MEDIA_ROOT, file_name)
    wb.save(p)
    down_load_path = DOMAIN_NAME + '/uploaded/' + os.path.basename(p)
    return down_load_path


def elevator_export(company_id):
    elevators = ElevatorInfo.objects.filter_active(service_id=company_id).order_by('create_time')
    company_name = CompanyInfo.objects.filter_active(id=company_id).first().name
    wb = xlwt.Workbook(encoding='utf-8')
    ws = wb.add_sheet(u'电梯')
    line = 1
    ws.write(0, 0, u'电梯简称')
    ws.write(0, 1, u'注册代码')
    ws.write(0, 2, u'电梯工号')
    ws.write(0, 3, u'内部编号')
    ws.write(0, 4, u'电梯出厂编号')
    ws.write(0, 5, u'设备性质')
    ws.write(0, 6, u'额定载重')
    ws.write(0, 7, u'层站门')
    ws.write(0, 8, u'电梯类型')
    ws.write(0, 9, u'使用状态')
    ws.write(0, 10, u'额定速度')
    ws.write(0, 11, u'电梯型号')
    ws.write(0, 12, u'制造商名称')
    ws.write(0, 13, u'安装单位名称')
    ws.write(0, 14, u'维保单位名称')
    ws.write(0, 15, u'使用单位名称')
    ws.write(0, 16, u'维保人员')
    ws.write(0, 17, u'救援人员')
    ws.write(0, 18, u'急救人员')
    ws.write(0, 19, u'是否通过备案')

    print u"开始", datetime.datetime.now()
    for elevator in elevators:
        ws.write(line, 0, elevator.elevator_name)
        ws.write(line, 1, elevator.register_code)
        ws.write(line, 2, elevator.elevator_no)
        ws.write(line, 3, elevator.internal_no)
        ws.write(line, 4, elevator.factory_no)
        elevator_property = elevator.elevator_property
        # if elevator_property == 10:
        #     e_p = u"安置房小区"
        # elif elevator_property == 20:
        #     e_p = u"商品房小区"
        # elif elevator_property == 20:
        #     e_p = u"医院、学校、机关事业单位"
        # else:
        #     e_p = u"其他"
        ws.write(line, 5, elevator.get_elevator_property_display())
        ws.write(line, 6, elevator.rated_load)
        ws.write(line, 7, elevator.stations)
        elevator_type = elevator.elevator_type
        # if elevator_type == 10:
        #     e_t = u"曳引与强制驱动电梯"
        # elif elevator_type == 20:
        #     e_t = u"液压驱动电梯"
        # elif elevator_type == 30:
        #     e_t = u"杂物电梯"
        # else:
        #     e_t = u"自动扶梯"
        ws.write(line, 8, elevator.get_elevator_type_display())
        usage_status = elevator.usage_status
        # if usage_status == 10:
        #     u_s = u"正常"
        # elif usage_status == 20:
        #     u_s = u"正常,临时停用"
        # elif usage_status == 30:
        #     u_s = u"正常,长期停用"
        # elif usage_status == 40:
        #     u_s = u"正常,拆除"
        # elif usage_status == 50:
        #     u_s = u"维修停用"
        # elif usage_status == 60:
        #     u_s = u"已报停用"
        # else:
        #     u_s = u"拆除"

        ws.write(line, 9, elevator.get_usage_status_display())
        ws.write(line, 10, elevator.rated_speed)
        ws.write(line, 11, elevator.elevator_model)
        ws.write(line, 12, elevator.product_company)
        ws.write(line, 13, elevator.installation_company)
        ws.write(line, 14, elevator.maintain_company_name)
        ws.write(line, 15, elevator.property_company.name)
        # p_list, valid = elevator.related_person()
        # # w_b = p_list[0]
        # # j_y = p_list[1]
        # # j_x = p_list[2]
        # wb_l = []
        # jy_l = []
        # jx_l = []
        # ll = elevator.persons()
        # wb_l = ll[0]
        # jy_l = ll[0]
        # jx_l = ll[0]
        # for e_p in w_b:
        #     wb_l.append(e_p.worker.auth_user.real_name)
        # wb_l = ';'.join(wb_l)
        # for e_p in j_y:
        #     jy_l.append(e_p.worker.auth_user.real_name)
        # jy_l = ';'.join(jy_l)
        # for e_p in j_x:
        #     jx_l.append(e_p.worker.auth_user.real_name)
        # jx_l = ';'.join(jx_l)
        # ws.write(line, 16, wb_l)
        # ws.write(line, 17, jy_l)
        # ws.write(line, 18, jx_l)
        registered = elevator.is_binded == 20
        registered = u'通过' if registered else u'未通过'
        ws.write(line, 19, registered)
        line += 1
    print u"结束", datetime.datetime.now()
    for i in range(line):
        ws.row(i).set_style(xlwt.easyxf('font:height ' + str(600)))
    for i in range(19):
        ws.col(i).width = 256 * 25
    t = datetime.datetime.now()
    t = t.strftime('%Y-%m-%d')
    file_name = unicode(company_name) + u'电梯' + unicode(t) + u'.xls'
    p = '%s/%s' % (MEDIA_ROOT, file_name)
    print type(wb)
    wb.save(p)
    down_load_path = DOMAIN_NAME + '/uploaded/' + os.path.basename(p)
    return down_load_path


def company_export(company_id):
    companys = CompanyInfo.objects.filter_active(service_id=company_id, company_type=300)
    company_name = CompanyInfo.objects.filter_active(id=company_id).first().name
    wb = xlwt.Workbook(encoding='utf-8')
    ws = wb.add_sheet(u'使用单位')
    line = 1
    ws.write(0, 0, u'单位名称')
    ws.write(0, 1, u'使用单位账户')
    ws.write(0, 2, u'负责人')
    ws.write(0, 3, u'负责人电话')
    ws.write(0, 4, u'法人')
    ws.write(0, 5, u'法人电话')
    ws.write(0, 6, u'社会统一信用代码')
    ws.write(0, 7, u'单位电话')
    for company in companys:
        ws.write(line, 0, company.name)
        ws.write(line, 1, company.auth_user.username)
        ws.write(line, 2, company.person_in_charge)
        ws.write(line, 3, company.person_in_charge_phone)
        ws.write(line, 4, company.legal_person)
        ws.write(line, 5, company.legal_phone)
        ws.write(line, 6, company.unified_code)
        ws.write(line, 7, company.company_telephone)
        line += 1
    for i in range(line):
        ws.row(i).set_style(xlwt.easyxf('font:height ' + str(600)))
    for i in range(8):
        ws.col(i).width = 256 * 25
    t = datetime.datetime.now()
    t = t.strftime('%Y-%m-%d')
    file_name = unicode(company_name) + u'使用单位' + unicode(t) + u'.xls'
    p = '%s/%s' % (MEDIA_ROOT, file_name)
    print type(wb)
    wb.save(p)
    down_load_path = DOMAIN_NAME + '/uploaded/' + os.path.basename(p)
    return down_load_path


def contract_import(company_id):
    contracts = Contract.objects.filter_active(service_id=company_id)
    company_name = CompanyInfo.objects.filter_active(id=company_id).first().name
    wb = xlwt.Workbook(encoding='utf-8')
    ws = wb.add_sheet(u'维保人员')
    line = 1
    ws.write(0, 0, u'合同名称')
    ws.write(0, 1, u'合同编号')
    ws.write(0, 2, u'合同类型')
    ws.write(0, 3, u'维保周期')
    ws.write(0, 4, u'合同开始时间')
    ws.write(0, 5, u'合同结束时间')
    ws.write(0, 6, u'签署日期')
    ws.write(0, 7, u'维保单位名称')
    ws.write(0, 8, u'使用单位名称')
    ws.write(0, 9, u'电梯注册代码')
    for contract in contracts:
        ws.write(line, 0, contract.contract_name)
        ws.write(line, 1, contract.contract_no)
        contract_type = contract.contract_type
        if contract_type == 10:
            c_t = u"质保"
        elif contract_type == 20:
            c_t = u"保养"
        else:
            c_t = u"维修"
        ws.write(line, 2, c_t)
        ws.write(line, 3, contract.maintain_cycle)
        ws.write(line, 4, contract.start_time)
        ws.write(line, 5, contract.end_time)
        ws.write(line, 6, contract.sign_time)
        ws.write(line, 7, company_name)
        ws.write(line, 8, contract.property_company.name)
        elevators = contract.elevator_contract_info.all()
        ele_register_code = []
        for i in elevators:
            ele_register_code.append(i.register_code)
        ele_register_code = ';'.join(ele_register_code)
        ws.write(line, 9, ele_register_code)
        line += 1
    for i in range(line):
        ws.row(i).set_style(xlwt.easyxf('font:height ' + str(600)))
    for i in range(9):
        ws.col(i).width = 256 * 25
    t = datetime.datetime.now()
    t = t.strftime('%Y-%m-%d')
    file_name = unicode(company_name) + u'合同' + unicode(t) + u'.xls'
    p = '%s/%s' % (MEDIA_ROOT, file_name)
    wb.save(p)
    down_load_path = DOMAIN_NAME + '/uploaded/' + os.path.basename(p)
    return down_load_path


def task_export(company_id, time_from=None, time_to=None):
    today = datetime.date.today()
    if time_from:
        time_from = datetime.datetime.strptime(time_from, "%Y-%m-%d").date()
        if time_to:
            time_to = datetime.datetime.strptime(time_to, "%Y-%m-%d").date()
            tasks = Task.objects.filter_active(day__gte=time_from, day__lte=time_to, service_id=company_id).order_by('day')
        else:
            tasks = Task.objects.filter_active(day__gte=time_from, service_id=company_id).order_by('day')
    else:
        tasks = Task.objects.filter_active(service_id=company_id).order_by('day')
    table = xlwt.Workbook(encoding='utf-8')
    sheet = table.add_sheet(u'维保计划')
    sheet.write(0, 0, u"维保计划日期")
    sheet.write(0, 1, u"电梯内部编号")
    sheet.write(0, 2, u"电梯注册代码")
    sheet.write(0, 3, u"使用单位")
    sheet.write(0, 4, u"工单编号")
    sheet.write(0, 5, u"工单状态")
    sheet.write(0, 6, u"保养类型")
    # sheet.write(0, 7, u"维保人员")
    line = 1
    for task in tasks:
        sheet.write(line, 0, str(task.day))
        sheet.write(line, 1, task.elevator.internal_no)
        sheet.write(line, 2, task.elevator.register_code)
        sheet.write(line, 3, task.elevator.property_company.name)
        sheet.write(line, 4, task.sn)
        sheet.write(line, 5, task.get_status_display())
        sheet.write(line, 6, task.get_maintain_type_display())
        worker_ids = json.loads(task.worker)
        # users = AuthUser.objects.filter(person__id__in=worker_ids)
        # name = u""
        # for user in users:
        #     name += user.real_name + u";"
        # sheet.write(line, 7, name)
        line += 1
    file_name = u'维保计划' + str(today) + u'.xls'
    p = '%s/%s' % (MEDIA_ROOT, file_name)
    table.save(p)
    down_load_path = DOMAIN_NAME + '/uploaded/' + os.path.basename(p)
    return down_load_path


class DataExportView(WdCreateAPIView):

    def post(self, request, *args, **kwargs):

        auth_user = self.request.user
        if auth_user.role != 20:
            return general_json_response(status.HTTP_200_OK, ErrorCode.PERMISSION_FAIL)
        company_id = auth_user.company_person.company.id
        request_type = self.request.data.get('request_type')
        if request_type == 'person':
            path = person_export(company_id)
            return general_json_response(status.HTTP_200_OK, ErrorCode.SUCCESS, path)
        elif request_type == 'company':
            path = company_export(company_id)
            return general_json_response(status.HTTP_200_OK, ErrorCode.SUCCESS, path)

        elif request_type == 'elevator':
            path = elevator_export(company_id)
            return general_json_response(status.HTTP_200_OK, ErrorCode.SUCCESS, path)
        elif request_type == 'contract':
            path = contract_import(company_id)
            return general_json_response(status.HTTP_200_OK, ErrorCode.SUCCESS, path)
        elif request_type == 'task':
            time_from = self.request.data.get("time_from", None)
            time_to = self.request.data.get("time_to", None)
            path = task_export(company_id, time_from, time_to)
            return general_json_response(status.HTTP_200_OK, ErrorCode.SUCCESS, path)
        else:
            return general_json_response(status.HTTP_200_OK, ErrorCode.INVALID_INPUT)

